//
//  MessageViewController.m
//  一点互助
//
//  Created by 张泊秋 on 16/8/19.
//  Copyright © 2016年 zhangboqiu. All rights reserved.
//

#import "MessageViewController.h"
#import "BlessingViewController.h"
#import "FriendViewController.h"
#import "UserModel.h"
#import "MemberViewController.h"
#import "BuddyInfoManager.h"
#import "ResponseManager.h"
#import "UserState.h"
#import "MessageTableViewCell.h"
#import "MessageAnotherHeaderView.h"
#import "MessageTableHeaderView.h"
#import "FriendsViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "EaseUI.h"

@interface MessageViewController ()<UITableViewDelegate,UITableViewDataSource,EMUserListViewControllerDataSource,EaseMessageViewControllerDelegate,EaseMessageViewControllerDataSource,EMContactManagerDelegate>
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *dataSource;
@property (strong, nonatomic) NSMutableArray *data;
@end

@implementation MessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    UserModel *user = [UserModel sharedUserModel];
//    if (!user.islogin) {
//        MemberViewController *vc = [[MemberViewController alloc]init];
//        [self.navigationController pushViewController:vc animated:YES];
//    }

    [self.view setBackgroundColor:[UIColor colorWithRed:0.8618 green:0.8618 blue:0.8618 alpha:1.0]];
    [self.view addSubview:self.tableView];
    self.title = @"消息";
    self.view.backgroundColor = RGBCOLOR(241.0f, 241.0f, 241.0f, 1);
    [self setupLeftItemWithImageName:@"消息-qianbao" action:@selector(leftTabbarButtonTaped:)];
    [self setupRightItemWithImageName:@"消息-xiaoxi" action:@selector(rightTabbarButtonTaped:)];
    [self addSubViews];
    
    [[EMClient sharedClient].contactManager asyncGetContactsFromServer:^(NSArray *aList) {
        PLLOG(@"%@",aList);
        for (int i = 0; i < aList.count; i++) {
            EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:aList[i] type:EMConversationTypeChat createIfNotExist:YES];
            PLLOG(@"%@",conversation);
        }

    } failure:^(EMError *aError) {
        PLLOG(@"%@",aError.description);
    }];
    
    [self getUser];
}

-(void)getMessage:(NSArray *)aMessages{
    
    for (EMMessage *message in aMessages) {
        EMMessageBody *msgBody = message.body;
        switch (msgBody.type) {
            case EMMessageBodyTypeText:
            {
                // 收到的文字消息
                EMTextMessageBody *textBody = (EMTextMessageBody *)msgBody;
                NSString *txt = textBody.text;
                NSLog(@"收到的文字是 txt -- %@",txt);
            }
                break;
            case EMMessageBodyTypeImage:
            {
                // 得到一个图片消息body
                EMImageMessageBody *body = ((EMImageMessageBody *)msgBody);
                NSLog(@"大图remote路径 -- %@"   ,body.remotePath);
                NSLog(@"大图local路径 -- %@"    ,body.localPath); // // 需要使用sdk提供的下载方法后才会存在
                NSLog(@"大图的secret -- %@"    ,body.secretKey);
                NSLog(@"大图的W -- %f ,大图的H -- %f",body.size.width,body.size.height);
                NSLog(@"大图的下载状态 -- %lu",body.downloadStatus);
                
                
                // 缩略图sdk会自动下载
                NSLog(@"小图remote路径 -- %@"   ,body.thumbnailRemotePath);
                NSLog(@"小图local路径 -- %@"    ,body.thumbnailLocalPath);
                NSLog(@"小图的secret -- %@"    ,body.thumbnailSecretKey);
                NSLog(@"小图的W -- %f ,大图的H -- %f",body.thumbnailSize.width,body.thumbnailSize.height);
                NSLog(@"小图的下载状态 -- %lu",body.thumbnailDownloadStatus);
            }
                break;
            case EMMessageBodyTypeLocation:
            {
                EMLocationMessageBody *body = (EMLocationMessageBody *)msgBody;
                NSLog(@"纬度-- %f",body.latitude);
                NSLog(@"经度-- %f",body.longitude);
                NSLog(@"地址-- %@",body.address);
            }
                break;
            case EMMessageBodyTypeVoice:
            {
                // 音频sdk会自动下载
                EMVoiceMessageBody *body = (EMVoiceMessageBody *)msgBody;
                NSLog(@"音频remote路径 -- %@"      ,body.remotePath);
                NSLog(@"音频local路径 -- %@"       ,body.localPath); // 需要使用sdk提供的下载方法后才会存在（音频会自动调用）
                NSLog(@"音频的secret -- %@"        ,body.secretKey);
                NSLog(@"音频文件大小 -- %lld"       ,body.fileLength);
                NSLog(@"音频文件的下载状态 -- %lu"   ,body.downloadStatus);
                NSLog(@"音频的时间长度 -- %lu"      ,body.duration);
            }
                break;
            case EMMessageBodyTypeVideo:
            {
                EMVideoMessageBody *body = (EMVideoMessageBody *)msgBody;
                
                NSLog(@"视频remote路径 -- %@"      ,body.remotePath);
                NSLog(@"视频local路径 -- %@"       ,body.localPath); // 需要使用sdk提供的下载方法后才会存在
                NSLog(@"视频的secret -- %@"        ,body.secretKey);
                NSLog(@"视频文件大小 -- %lld"       ,body.fileLength);
                NSLog(@"视频文件的下载状态 -- %lu"   ,body.downloadStatus);
                NSLog(@"视频的时间长度 -- %lu"      ,body.duration);
                NSLog(@"视频的W -- %f ,视频的H -- %f", body.thumbnailSize.width, body.thumbnailSize.height);
                
                // 缩略图sdk会自动下载
                NSLog(@"缩略图的remote路径 -- %@"     ,body.thumbnailRemotePath);
                NSLog(@"缩略图的local路径 -- %@"      ,body.thumbnailLocalPath);
                NSLog(@"缩略图的secret -- %@"        ,body.thumbnailSecretKey);
                NSLog(@"缩略图的下载状态 -- %lu"      ,body.thumbnailDownloadStatus);
            }
                break;
            case EMMessageBodyTypeFile:
            {
                EMFileMessageBody *body = (EMFileMessageBody *)msgBody;
                NSLog(@"文件remote路径 -- %@"      ,body.remotePath);
                NSLog(@"文件local路径 -- %@"       ,body.localPath); // 需要使用sdk提供的下载方法后才会存在
                NSLog(@"文件的secret -- %@"        ,body.secretKey);
                NSLog(@"文件文件大小 -- %lld"       ,body.fileLength);
                NSLog(@"文件文件的下载状态 -- %lu"   ,body.downloadStatus);
            }
                break;
                
            default:
                break;
        }
    }
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    UserState *user = [[UserState alloc]init];
    if (user.invitationArr.count != 0) {
        self.dataSource = [user.invitationArr mutableCopy];
        PLLOG(@"%@",self.dataSource);
        [self.tableView reloadData];
    }
    if (user.messageArr.count != 0) {
//        [self.data addObjectsFromArray:user.messageArr];
        self.data = [user.messageArr copy];
        [self getMessage:self.data];
    }
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = YES;
}
-(void)addSubViews{
    UINib *nib = [UINib nibWithNibName:@"MessagetableHeaderView" bundle:nil];
    [self.tableView registerNib:nib forHeaderFooterViewReuseIdentifier:@"MessagetableHeaderView"];
    UINib *nib2 = [UINib nibWithNibName:@"MessageAnotherHeaderView" bundle:nil];
    [self.tableView registerNib:nib2 forHeaderFooterViewReuseIdentifier:@"MessageAnotherHeaderView"];
    UINib *nib3 = [UINib nibWithNibName:@"MessageTableViewCell" bundle:nil];
    [self.tableView registerNib:nib3 forCellReuseIdentifier:@"MessageTableViewCell"];
}

- (void)leftTabbarButtonTaped:(UIButton *)sender {
    
    BlessingViewController *blessingVC = [[BlessingViewController alloc]init];
    [self.navigationController pushViewController:blessingVC animated:YES];
    
}
- (void)rightTabbarButtonTaped:(UIButton *)sender {
    FriendsViewController *friendVC = [[FriendsViewController alloc]init];
    [self.navigationController pushViewController:friendVC animated:YES];
    
}
-(void)getUser{
    __weak typeof(self) myself = self;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *dic = [defaults objectForKey:@"userInfo"];
    NSString *idStr = dic[@"id"];
    NSDictionary *parameters = @{@"user_id":idStr};
   [ResponseManager startPostRequestWithURLString:kGetFriendsListURL parameters:parameters completionHandler:^(FBResponse *response) {
           if (response.success) {
               PLLOG(@"%@",response.resultValue);
               myself.data = [response.resultValue mutableCopy];
               [myself.tableView reloadData];
           }else{
               PLLOG(@"%@",response.resultDesc);
           }
   }];
}
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor whiteColor];
    }
    return _tableView;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 0;
    }
    else{
        return self.data.count + self.dataSource.count;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MessageTableViewCell" forIndexPath:indexPath];
    if (self.dataSource.count == 0 && self.data.count == 0) {
        return cell;
    }else if (self.dataSource.count != 0 && self.data.count == 0){
        cell.niceNameLabel.text = self.dataSource[indexPath.row][@"username"];
        return cell;
    }else if (self.dataSource.count != 0 && self.data.count != 0){
        if (indexPath.row <= self.dataSource.count) {
            cell.niceNameLabel.text = self.dataSource[indexPath.row][@"username"];
            return cell;
        }else{
            cell.niceNameLabel.text = self.data[indexPath.row][@"user_nicename"];
            NSString *str = self.data[indexPath.row][@"avatar"];
            NSString *newStr = [NSString stringWithFormat:@"http://www.scxxhs.com/huzhu/%@",str];
            [cell.image sd_setImageWithURL:[NSURL URLWithString:newStr] placeholderImage:[UIImage imageNamed:@"趣味-img1"]];
            cell.act = [self.data[indexPath.row][@"act"]integerValue];
            return cell;
        }
    }else{
        cell.niceNameLabel.text = self.data[indexPath.row][@"user_nicename"];
        NSString *str = self.data[indexPath.row][@"avatar"];
        NSString *newStr = [NSString stringWithFormat:@"http://www.scxxhs.com/huzhu/%@",str];
        [cell.image sd_setImageWithURL:[NSURL URLWithString:newStr] placeholderImage:[UIImage imageNamed:@"趣味-img1"]];
        cell.act = [self.data[indexPath.row][@"act"]integerValue];
        return cell;
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        MessageTableHeaderView *view = [MessageTableHeaderView loadHeader];
        return view;
    }
    else{
        MessageAnotherHeaderView *view = [MessageAnotherHeaderView loadHeaderView];
        view.label.text = [NSString stringWithFormat:@"%lu",self.dataSource.count+self.data.count];
        return view;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    EaseMessageViewController *vc = [[EaseMessageViewController alloc]initWithConversationChatter:self.data[indexPath.row][@"mobile"] conversationType:EMConversationTypeChat];
    vc.title = self.data[indexPath.row][@"user_nicename"];
    [self.navigationController pushViewController:vc animated:YES];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
        return 70 * kScreenHeightScale;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
        return 80 * kScreenHeightScale;
}
-(NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
-(NSMutableArray *)data{
    if (!_data) {
        _data = [NSMutableArray array];
    }
    return _data;
}
@end
